package cn.tedu.sp11.ItemFallback;

import cn.tedu.sp01.vo.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class fallback implements FallbackProvider {
    //当前降级类对哪个服务有效
    //如果返回"item-service",那么当前降级类只对商品服务有效
    //若返回 "*" 或null  对所有服务都有效
    @Override
    public String getRoute() {
        return "item-service";
    }

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            //http协议状态
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                
               String r= JsonResult.err().msg("后台运行错误").toString();
               return new ByteArrayInputStream(r.getBytes("UTF-8"));
            }

            @Override
            public HttpHeaders getHeaders() {
              HttpHeaders h=new HttpHeaders();
              h.setContentType(MediaType.APPLICATION_JSON);
              return h;
            }
        };
    }
}
